package com.seednia.foundation.framework.dto;

import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 * Class used to return query result.
 * Not bein used at the moment.
 * 
 * @author Young Suk Ahn
 *
 * @param <T>
 */
@XmlRootElement(name = "QueryResult", 
	namespace = "http://seednia.com/foundation/1.0")
@XmlType(name = "QueryResult")
@XmlAccessorType(XmlAccessType.FIELD)
public class QueryResult<T> {
	
	private String indexName; // If SearchEngine is used, <DtoName>Index, otherwise <DtoName>Dao
	private String indexType;
	
	private List<Map.Entry<String, Long>> executionTimes = null; // List of commands and the time elapsed in milleseconds
	private long startTotalExecutionTime = 0;
	private long endTotalExecutionTime = 0;
	
	// For paging
	private QueryParams queryParams;
	private long totalCount = 0;
	
	private List<T> result = null;


	public QueryParams getQueryParams() {
		return queryParams;
	}
	public void setQueryParams(QueryParams queryParams) {
		this.queryParams = queryParams;
	}

	public long getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(long totalCount) {
		this.totalCount = totalCount;
	}

	public List<Map.Entry<String, Long>> getExecutionTimes() {
		return executionTimes;
	}

	public void setResult(List<T> result) {
		this.result = result;
	}
	public List<T> getResult() {
		return this.result;
	}
	
	
	public void init(QueryParams queryParams)
	{
		this.startTotalExecutionTime = System.currentTimeMillis();
		this.queryParams = queryParams;
	}
	
	public long getTotalElapsedTime()
	{
		return this.endTotalExecutionTime - this.startTotalExecutionTime;
	}
	
	/**
	 * This is not thread safe
	 * @param command
	 */
	public void commandStarted(String command)
	{
		if (executionTimes == null)
			executionTimes = new ArrayList<Map.Entry<String, Long>>();
		Map.Entry<String, Long> elapsedTimeEntry = new AbstractMap.SimpleEntry<String, Long>(command, System.currentTimeMillis());
		executionTimes.add(elapsedTimeEntry);
	}
	
	public void commandEnded(String command)
	{
		Map.Entry<String, Long> elapsedTimeEntry = executionTimes.get(executionTimes.size()-1);
		if (elapsedTimeEntry.getKey().equals(command))
			elapsedTimeEntry.setValue(System.currentTimeMillis()-elapsedTimeEntry.getValue());
		this.endTotalExecutionTime = System.currentTimeMillis();
	}
	
	
}
